import { log, Asset, assetManager, error, Node, Vec3, sp, tween, Layers, find, Camera, v2, UITransform, v3, isValid, CCObject } from 'cc';
import { ITEM_TYPE } from '../common/GameConst';

export default class Utils {

    //检查是否同一天
    public static checkIsToDay(time: number): boolean {

        var date = new Date(time);
        var dateNow = new Date()
        let bSameDay = false;

        if (date.getFullYear() == dateNow.getFullYear() &&
            date.getMonth() == dateNow.getMonth() &&
            date.getDate() == dateNow.getDate()
        ) {
            bSameDay = true;
        }
        return bSameDay;
    }



    public static getRandom(lower, upper): number {
        return Math.random() * (upper - lower) + lower;
    };

    public static getRandomInt(lower, upper): number {
        return Math.floor(Math.random() * (upper - lower)) + lower;
    };

    public static seed: number = 5;

    public static seedRandom(): number {
        return Utils.getRandom(0, 1);
        // this.seed = (this.seed * 9301 + 49297) % 233280;
        // return this.seed / 233280.0;
    }

    public static seedRandomInt(lower, upper): number {
        return Utils.getRandomInt(lower, upper);
        // return Math.floor(Utils.seedRandom() * (upper - lower)) + lower;
    }

    // public static formatNumber(num: number, afterdot: number = 1) {
    //     num = Math.floor(num);
    //     return BigNumber.getLargeString(num);
    // };
    public static getPowNum(p) {
        return Math.pow(10, p);
    };


    // static showTip(value: string) {
    //     if (sys.platform == sys.WECHAT_GAME) {
    //         wx.showToast({ title: value, icon: 'none', duration: 1500 })
    //     }
    // }

    static formatDate(t) {
        var date = new Date(t);
        var YY = date.getFullYear() + '-';
        var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
        var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
        var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
        var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
        return YY + MM + DD + " " + hh + mm + ss;
    }

    public static cloneObj(obj: any) {
        obj = JSON.stringify(obj);
        obj = JSON.parse(obj);
        return obj;
    }

    public static getTimeStrByS(second: number) {
        second = Math.floor(second);
        if (second < 0) second = 0;
        var d = Math.floor(second / 3600 / 24);
        second -= d * 3600 * 24;
        var h = Math.floor(second / 3600);
        second -= h * 3600;
        var m = Math.floor(second / 60);
        second -= m * 60;
        var front = "00";
        if (h > 9) {
            front = "" + h;
        } else {
            front = "0" + h;
        }
        var mid = "00";
        if (m > 9) {
            mid = "" + m;
        } else {
            mid = "0" + m;
        }
        var back = "00";
        if (second > 9) {
            back = "" + second;
        } else {
            back = "0" + second;
        }

        if (d > 0) {
            return d + "天" + h + "时" + m + "分";
        }
        else {
            var longTime = h > 0;
            if (longTime) {
                return front + ":" + mid;
            } else {
                return mid + ":" + back;//+ '秒';
            }
        }
    }

    public static getClockStrByS(second: number, showsecond: boolean = true, showhour: boolean = true) {
        second = Math.floor(second);
        if (second < 0) second = 0;
        var h = Math.floor(second / 3600);
        second -= h * 3600;
        var m = Math.floor(second / 60);
        second -= m * 60;
        var front = "00";
        if (h > 9) {
            front = "" + h;
        } else {
            front = "0" + h;
        }
        var mid = "00";
        if (m > 9) {
            mid = "" + m;
        } else {
            mid = "0" + m;
        }

        let str = ""
        if (showhour) {
            str += front;
            str += ":"
        }
        str += mid;

        if (showsecond)
            str += ":" + (second < 10 ? "0" : "") + second;

        return str
    }

    public static checkObjEmpty(obj: any) {
        if (obj) {
            for (var i in obj) {
                return false;
            }
            return true;
        } else {
            return true;
        }
    }

    public static checkOrderOver(orderTime: number) {
        var date = new Date(orderTime);
        var dateNow = new Date();

        if (date.getFullYear() == dateNow.getFullYear() &&
            date.getMonth() == dateNow.getMonth() &&
            date.getDate() == dateNow.getDate()
        ) {
            return false;
        } else {
            return true;
        }
    }

    public static loadBundler(name: string) {
        return new Promise((resolve, reject) => {
            assetManager.loadBundle(name, (err, ret) => {
                console.log(ret)
                resolve(null);
            })
        })
    }

    public static loadRes(path: string, bundle: string, type: typeof Asset, callback: any = null) {
        return new Promise((resolve, reject) => {
            if (!assetManager.getBundle(bundle)) {
                console.log(bundle);
            }
            let ret = assetManager.getBundle(bundle).get(path, type);
            if (ret) {
                if (callback) callback(null, ret);
                resolve(ret);
                return;
            }

            assetManager.getBundle(bundle).load(path, type, (err, ret: Asset) => {
                if (err) {
                    console.warn("加载错误：", path, err);
                    if (callback) callback(err, null);
                    reject(null);
                }
                else {
                    if (callback) callback(null, ret);
                    resolve(ret);
                }
            });
        })
    }

    public static weight(v: number[]): number {
        var mTotalWeight = 0;
        for (var i = 0; i < v.length; ++i) {
            mTotalWeight += v[i];
        }
        if (mTotalWeight <= 0) return -1;
        var randnum = Math.round(Math.random() * Number.MAX_VALUE) % mTotalWeight;
        for (var i = 0; i < v.length; ++i) {
            if (randnum < v[i]) {
                return i;
            }
            else {
                randnum -= v[i];
            }
        }
        return -1;
    }

    public static shuffle(arr: any[]) {
        for (let i = arr.length - 1; i >= 0; i--) {
            let rIndex = Math.floor(Math.random() * (i + 1));
            let temp = arr[rIndex];
            arr[rIndex] = arr[i];
            arr[i] = temp;
        }
        return arr;
    }

    public static getDate(time: number): string {
        var now = new Date(time),
            y = now.getFullYear(),
            m = now.getMonth() + 1,
            d = now.getDate();
        return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
    }

    //货币进位
    public static goldCrarryBit(gold: number): string {

        var array = [
            [100000000, 'N'],
            [10000000, 'T'],
            [1000000, 'G'],
            [100000, 'M'],
            [10000, 'K'],
            [1000, 'B'],
        ];
        for (var i = 0; i < array.length; i++) {
            var value = gold / (array[i][0] as number);
            if (value > 1) {
                return '' + value.toFixed(1) + array[i][1];
            }
        }
        return gold.toString();
    }
    //定点数
    public static fixFloat(val: number, count: number = 2) {
        var a = Math.pow(10, count)
        return Math.floor(val * a) / a;
    }

    public static flyAnim(type: ITEM_TYPE, starNode: Node, targetNode: Node, count: number, radius: number, callback: Function) {
        let getPoint = (r, ox, oy, count) => {
            var point = []; //结果
            var radians = (Math.PI / 180) * Math.round(360 / count), //弧度
                i = 0;
            for (; i < count; i++) {
                var x = ox + r * Math.sin(radians * i),
                    y = oy + r * Math.cos(radians * i);

                point.unshift(v2(x, y)); //为保持数据顺时针
            }
            return point;
        }

        let start = starNode.worldPosition;
        var array = getPoint(radius, start.x, start.y, count);

        var nodeArray = new Array();
        for (var i = 0; i < array.length; i++) {
            var gold = window['PoolMgr'].Instance().get(type)
            gold.setWorldScale(v3(0.7, 0.7, 0.7));
            // gold.zIndex = GameConst.WIN_LAYER.TIP;
            gold.parent = find("Canvas")
            var randPos = v3(array[i].x + Utils.getRandomInt(0, 50), array[i].y + Utils.getRandomInt(0, 50), 1);
            gold.setWorldPosition(start);
            nodeArray.push({ gold, randPos });
        }

        var notPlay = false;
        let dstPos = targetNode.worldPosition;

        for (let i = 0; i < nodeArray.length; i++) {
            let pos = nodeArray[i].randPos;
            let node = nodeArray[i].gold;
            nodeArray[i].gold.id = i;

            tween(node).to(0.2, { worldPosition: pos }).delay(i * 0.03).to(0.7, { worldPosition: v3(dstPos.x, dstPos.y, 1) }).call(() => {
                if (!notPlay) {
                    notPlay = true;
                    tween(targetNode).to(0.1, { scale: v3(2, 2, 2) }).to(0.1, { scale: v3(1, 1, 1) }).call(() => {
                        notPlay = false;
                    }).start()
                }
                callback(node.id == nodeArray.length - 1);
                window['PoolMgr'].Instance().put(node.name, node);
            }).start()
        }
    }

    static formatString(s: string, ...arg: string[]) {

        for (var i = 0; i < arg.length; i++) {
            var reg = new RegExp("\\{" + i + "\\}", "gm");
            s = s.replace(reg, arg[i]);
        }
        return s;
    }
    // static convetOtherNodeSpaceAR(sourceNode:Node, targetNode:Node)
    // {
    //     var worldP:Vec2=sourceNode.convertToWorldSpaceAR(v2(0,0))        
    //     return targetNode.convertToNodeSpaceAR(worldP)
    // }
    static count(obj: any) {
        if (!obj) return 0;
        var num = 0;
        for (var k in obj) {
            num++;
        }
        return num;
    };
    static copy(obj: any) {
        var newObj = Object.create(obj);
        Object.assign(newObj, obj);
        return newObj;
    }
    // static setGray(icon:Sprite, isGray:boolean) {
    //     if (isGray) {
    //         icon.setMaterial(0, Material.getBuiltinMaterial('2d-gray-sprite'));
    //     } else {
    //         icon.setMaterial(0, Material.getBuiltinMaterial('2d-sprite'));
    //     }
    // }

    static async playSkAni(file: string, name: string, parent: Node, pos: Vec3, removetime: number = -1) {
        var node = new Node()
        node.parent = parent;
        node.position = pos;
        node.layer = Layers.BitMask.UI_2D;
        // let uit = node.addComponent(UITransform);
        // uit.width = 200;
        // uit.height = 130;
        var skd = node.addComponent(sp.Skeleton);
        var data = await Utils.loadRes(file, "spine", sp.SkeletonData) as sp.SkeletonData;
        skd.skeletonData = data;
        skd.setAnimation(0, name, false);
        if (removetime != -1) {
            tween(node).delay(removetime).call(() => {
                node.removeFromParent();
                node.destroy();
            }).start();
        }
        return node;
    }
};